import blue
import uix
import uiutil
import xtriui
import util
import uiconst
import listentry
import uicls
from mapcommon import STARMODE_SOV_CHANGE, STARMODE_FACTION
COLOR_LIGHT_BLUE = (0.21, 0.62, 0.74, 1.0)
COLOR_DARK_BLUE = (0.0, 0.52, 0.67, 1.0)
BAR_COLORS = [COLOR_LIGHT_BLUE, COLOR_DARK_BLUE]
TIME_SLIDER_HEIGHT = 40
TIME_BAR_HEIGHT = 19
MENU_HEIGHT = 28
LABEL_HEIGHT = 10
LOCATION_HEIGHT = ((18 + LABEL_HEIGHT) + 4)
HEADER_HEIGHT = (((MENU_HEIGHT + LOCATION_HEIGHT) + (LABEL_HEIGHT * 2)) + 16)
LINE_HEIGHT = 8
ACTIVEKILL_HEIGHT = 10

class SovereigntyTab(object):
    __guid__ = 'sovereignty.SovereigntyTab'
    (SolarSystem, Constellation, Region, World, Changes,) = range(1, 6)

LINK_COLOR = '<color=0xffddaa44>%s</color>'
SHOW_INFO_URL = '<url=showinfo:%d//%d>%s</url>'

class SovereigntyOverviewWnd(uicls.Window):
    __guid__ = 'form.SovereigntyOverviewWnd'
    __notifyevents__ = ['OnSessionChanged',
     'OnSystemStatusChanged',
     'OnStateSetupChance',
     'OnSovereigntyChanged']

    def ApplyAttributes(self, attributes):
        uicls.Window.ApplyAttributes(self, attributes)
        self.locationScope = settings.user.ui.Get('sovDashboardLocationScope', SovereigntyTab.SolarSystem)
        self.SetCaption(mls.UI_SHARED_MAPSOVEREIGNTY)
        self.SetMinSize([420, 400])
        self.SetWndIcon()
        self.SetTopparentHeight(0)
        self.solarSystemID = eve.session.solarsystemid2
        self.constellationID = eve.session.constellationid
        self.regionID = eve.session.regionid
        self.ConstructLayout()
        self.scope = 'all'
        self.ResetLocation()



    def SetLocation(self, solarSystemID, constellationID, regionID, restoreTab = False):
        self.solarSystemID = solarSystemID
        self.constellationID = constellationID
        self.regionID = regionID
        selectedTab = SovereigntyTab.World
        self.pushButtons.DisableButton(mls.CONSTELLATION)
        self.pushButtons.DisableButton(mls.SYSTEM)
        if (self.regionID is not None):
            selectedTab = SovereigntyTab.Region
        if (self.constellationID is not None):
            selectedTab = SovereigntyTab.Constellation
            self.pushButtons.EnableButton(mls.CONSTELLATION)
        if (self.solarSystemID is not None):
            self.pushButtons.EnableButton(mls.SYSTEM)
            selectedTab = SovereigntyTab.SolarSystem
        if (restoreTab and (self.locationScope > selectedTab)):
            selectedTab = self.locationScope
        self.pushButtons.SelectPanelByArgs(selectedTab)



    def ConstructLayout(self):
        self.sr.header = uicls.Container(name='header', parent=self.sr.main, align=uiconst.TOTOP, pos=(0,
         0,
         0,
         HEADER_HEIGHT), padding=(0,
         const.defaultPadding,
         0,
         const.defaultPadding))
        self.sr.menu = uicls.Container(name='menu', parent=self.sr.header, align=uiconst.TOTOP, pos=(0,
         0,
         0,
         MENU_HEIGHT), padding=(2, 0, 2, 0))
        self.sr.location = uicls.Container(name='location', parent=self.sr.header, align=uiconst.TOTOP, pos=(0,
         0,
         0,
         LOCATION_HEIGHT), padding=(4, 4, 6, 0))
        self.sr.line = uicls.Container(name='line', parent=self.sr.header, align=uiconst.TOTOP, pos=(0,
         0,
         0,
         LINE_HEIGHT), padding=(0, 2, 0, 0))
        uicls.Line(parent=self.sr.line, align=uiconst.TOTOP, color=(0.0, 0.0, 0.0, 0.25))
        uicls.Line(parent=self.sr.line, align=uiconst.TOTOP)
        self.sr.activekill = uicls.Container(name='activekill', parent=self.sr.header, align=uiconst.TOTOP, pos=(0,
         0,
         0,
         (LABEL_HEIGHT * 2)), padding=(0, 0, 0, 0))
        self.sr.regionalOverview = uicls.Container(name='regionalOverview', parent=self.sr.main, align=uiconst.TOALL, padding=(0, 4, 0, 0))
        self.sr.worldOverview = uicls.Container(name='worldOverview', parent=self.sr.main, align=uiconst.TOALL, padding=(0, 4, 0, 0), state=uiconst.UI_HIDDEN)
        self.CreateLocationInfo()
        self.CreateActiveKillInfo()
        self.DrawStationsOutposts()
        self.DrawDivider()
        self.DrawInfrastructureHubs()
        self.DrawChanges()
        self.CreateMenu()



    def LoadPushButtonPanel(self, scope):
        self.locationScope = scope
        settings.user.ui.Set('sovDashboardLocationScope', self.locationScope)
        self.Refresh()



    def GetLocationFromScope(self):
        locationID = ''
        if (self.locationScope == SovereigntyTab.World):
            locationID = None
        if (self.locationScope == SovereigntyTab.Changes):
            locationID = None
        elif (self.locationScope == SovereigntyTab.SolarSystem):
            locationID = self.solarSystemID
        elif (self.locationScope == SovereigntyTab.Constellation):
            locationID = self.constellationID
        elif (self.locationScope == SovereigntyTab.Region):
            locationID = self.regionID
        return locationID



    def DrawChanges(self):
        l = uicls.Line(parent=self.sr.worldOverview, align=uiconst.TOTOP, color=(0.0, 0.0, 0.0, 0.25))
        l = uicls.Line(parent=self.sr.worldOverview, align=uiconst.TOTOP)
        changeContainer = uicls.Container(name='changeContainer', parent=self.sr.worldOverview, align=uiconst.TOALL, pos=(0, 0, 0, 0), padding=(const.defaultPadding,
         6,
         const.defaultPadding,
         6))
        self.sr.changesScroll = uicls.Scroll(parent=changeContainer)



    def DrawStationsOutposts(self):
        self.sr.stationsoutposts = uicls.Container(parent=self.sr.regionalOverview, align=uiconst.TOTOP, state=uiconst.UI_NORMAL, height=24)
        stationsoutposts = self.sr.stationsoutposts
        textContainer = uicls.Container(name='textContainer', parent=stationsoutposts, align=uiconst.TOALL, pos=(0, 0, 0, 0), padding=(0, 0, 0, 0))
        leftContainer = uicls.Container(name='leftContainer', parent=textContainer, align=uiconst.TOALL, pos=(0, 0, 0, 0), padding=(3, 0, 0, 0))
        rightContainer = uicls.Container(name='rightContainer', parent=textContainer, align=uiconst.TORIGHT, pos=(0, 0, 15, 0), padding=(0, 0, 3, 0))
        t = uicls.Label(text=('<b>%s</b>' % mls.UI_GENERIC_OVERVIEW), parent=leftContainer, state=uiconst.UI_DISABLED, left=3, align=uiconst.CENTERLEFT)
        rightContainer.width = t.width
        stationsoutposts.height = max(20, (t.textheight + 6))
        l = uicls.Line(parent=stationsoutposts, align=uiconst.TOTOP, color=(0.0, 0.0, 0.0, 0.25))
        l = uicls.Line(parent=stationsoutposts, align=uiconst.TOTOP)
        l = uicls.Line(parent=stationsoutposts, align=uiconst.TOBOTTOM)
        l = uicls.Line(parent=stationsoutposts, align=uiconst.TOBOTTOM, color=(0.0, 0.0, 0.0, 0.25))
        stationsoutpostsResults = uicls.Container(name='stationsoutpostsResults', parent=self.sr.regionalOverview, align=uiconst.TOTOP, state=uix.UI_PICKCHILDREN, pos=(0, 0, 0, 100), padding=(const.defaultPadding,
         6,
         const.defaultPadding,
         6))
        self.sr.stationsoutpostsResults = stationsoutpostsResults
        self.sr.stationOutpostsScroll = uicls.Scroll(parent=stationsoutpostsResults)



    def DrawDivider(self):
        divPar = uicls.Container(name='divPar', align=uiconst.TOBOTTOM, pos=(0,
         0,
         0,
         const.defaultPadding), parent=self.sr.stationsoutpostsResults, idx=0)
        divider = xtriui.Divider(uicls.Container(name='divider', align=uiconst.TOALL, pos=(0, 0, 0, 0), parent=divPar, state=uiconst.UI_NORMAL, idx=0))
        divider.Startup(self.sr.stationsoutpostsResults, 'height', 'y', 57, 800)
        divider.OnSizeChanged = self._OnContentSizeChanged
        divider.OnSizeChangeStarting = self._OnContentSizeChangeStarting
        divider.OnSizeChanging = self._OnContentSizeChanging
        l = uicls.Line(parent=divider, align=uiconst.CENTER, width=6, height=1)
        self.sr.divider = divider



    def ApplyContentPortion(self):
        if ((not util.GetAttrs(self, 'sr', 'stationsoutpostsResults')) or (getattr(self, '_ignorePortion', False) or ((not uiutil.IsVisible(self.sr.stationsoutpostsResults)) or (not util.GetAttrs(self, 'sr', 'infrastructurehubs'))))):
            return 
        portion = settings.user.ui.Get('stationsoutpostsPortion', 0.5)
        minResultSpace = (self.sr.infrastructurehubs.height + 18)
        if (self.sr.infrastructurehubsResults.state != uix.UI_HIDDEN):
            minResultSpace += 50
        else:
            portion = 1.0
        (sl, st, sw, sh,) = self.sr.regionalOverview.GetAbsolute()
        (rcl, rct, rcw, rch,) = self.sr.infrastructurehubsResults.GetAbsolute()
        spread = ((sh - self.sr.stationsoutposts.height) - self.sr.header.height)
        height = int((spread * portion))
        self.sr.stationsoutpostsResults.height = min(height, (spread - minResultSpace))



    def _OnContentSizeChanging(self, *args):
        if (self.sr.stationsoutpostsResults.height < self._maxContentHeight):
            if self.sr.stack:
                (l, t, w, h,) = self.sr.stack.GetAbsolute()
            else:
                (l, t, w, h,) = self.GetAbsolute()
            minResultSpace = (self.sr.infrastructurehubs.height + 18)
            if (self.sr.infrastructurehubsResults.state != uix.UI_HIDDEN):
                minResultSpace += 50
            if (((t + h) - eve.triapp.uilib.y) < minResultSpace):
                if self.sr.stack:
                    self.sr.stack.height = ((eve.triapp.uilib.y + minResultSpace) - t)
                else:
                    self.height = ((eve.triapp.uilib.y + minResultSpace) - t)



    def _OnContentSizeChangeStarting(self, *args):
        self._ignorePortion = True
        (l, t, w, h,) = self.sr.stationsoutpostsResults.GetAbsolute()
        minResultSpace = (self.sr.infrastructurehubs.height + 18)
        if (self.sr.infrastructurehubsResults.state != uix.UI_HIDDEN):
            minResultSpace += 50
        maxValue = ((eve.triapp.uilib.desktop.height - t) - minResultSpace)
        self.sr.divider.SetMinMax(maxValue=maxValue)
        self._maxContentHeight = maxValue



    def _OnContentSizeChanged(self, *args):
        (sl, st, sw, sh,) = self.sr.regionalOverview.GetAbsolute()
        probesPart = (self.sr.stationsoutposts.height + self.sr.stationsoutpostsResults.height)
        (rcl, rct, rcw, rch,) = self.sr.infrastructurehubsResults.GetAbsolute()
        resultPart = (self.sr.infrastructurehubs.height + rch)
        portion = (probesPart / float((sh - self.sr.header.height)))
        settings.user.ui.Set('stationsoutpostsPortion', portion)
        self._ignorePortion = False



    def DrawInfrastructureHubs(self):
        self.sr.infrastructurehubs = uicls.Container(parent=self.sr.regionalOverview, align=uiconst.TOTOP, state=uiconst.UI_NORMAL, height=24)
        infrastructurehubs = self.sr.infrastructurehubs
        textContainer = uicls.Container(name='textContainer', parent=infrastructurehubs, align=uiconst.TOALL, pos=(0, 0, 0, 0), padding=(0, 0, 0, 0))
        leftContainer = uicls.Container(name='leftContainer', parent=textContainer, align=uiconst.TOALL, pos=(0, 0, 0, 0), padding=(3, 0, 0, 0))
        rightContainer = uicls.Container(name='rightContainer', parent=textContainer, align=uiconst.TORIGHT, pos=(0, 0, 15, 0), padding=(0, 0, 3, 0))
        t = uicls.Label(text=('<b>%s</b>' % mls.SOVEREIGNTY_DEVELOPMENTINDICES), parent=leftContainer, state=uiconst.UI_DISABLED, align=uiconst.CENTERLEFT, left=3)
        rightContainer.width = t.width
        infrastructurehubs.height = max(20, (t.textheight + 6))
        l = uicls.Line(parent=infrastructurehubs, align=uiconst.TOTOP, color=(0.0, 0.0, 0.0, 0.25))
        l = uicls.Line(parent=infrastructurehubs, align=uiconst.TOTOP)
        l = uicls.Line(parent=infrastructurehubs, align=uiconst.TOBOTTOM)
        l = uicls.Line(parent=infrastructurehubs, align=uiconst.TOBOTTOM, color=(0.0, 0.0, 0.0, 0.25))
        infrastructurehubsResults = uicls.Container(name='infrastructurehubsResults', parent=self.sr.regionalOverview, align=uiconst.TOALL, state=uix.UI_PICKCHILDREN, pos=(0, 0, 0, 0), padding=(const.defaultPadding,
         6,
         const.defaultPadding,
         6))
        self.sr.infrastructurehubsResults = infrastructurehubsResults
        self.sr.infrastructurehubsScroll = uicls.Scroll(parent=infrastructurehubsResults)



    def CreateHeaderText(self):
        text = ''
        if (self.locationScope == SovereigntyTab.World):
            text = ('<b>%s</b>' % mls.SOVEREIGNTY_WORLDSTATUS)
            return text
        else:
            if (self.locationScope == SovereigntyTab.Changes):
                text = ('<b>%s</b>' % mls.SOVEREIGNTY_RECENTCHANGES)
                return text
            mapSvc = sm.GetService('map')
            systemItem = mapSvc.GetItem(self.solarSystemID)
            constItem = mapSvc.GetItem(self.constellationID)
            regItem = mapSvc.GetItem(self.regionID)
            text = ''
            if (self.locationScope == SovereigntyTab.SolarSystem):
                if util.IsWormholeRegion(self.regionID):
                    text += regItem.itemName
                    text += ' / '
                    text += constItem.itemName
                else:
                    text += (SHOW_INFO_URL % (regItem.typeID,
                     self.regionID,
                     regItem.itemName))
                    text += ' / '
                    text += (SHOW_INFO_URL % (constItem.typeID,
                     self.constellationID,
                     constItem.itemName))
                text += ' / '
                text += (SHOW_INFO_URL % (systemItem.typeID,
                 self.solarSystemID,
                 ('<b>%s</b>' % systemItem.itemName)))
            elif (self.locationScope == SovereigntyTab.Constellation):
                if util.IsWormholeRegion(self.regionID):
                    text += regItem.itemName
                    text += ' / '
                    text += constItem.itemName
                else:
                    text += (SHOW_INFO_URL % (regItem.typeID,
                     self.regionID,
                     regItem.itemName))
                    text += ' / '
                    text += (SHOW_INFO_URL % (constItem.typeID,
                     self.constellationID,
                     ('<b>%s</b>' % constItem.itemName)))
            elif (self.locationScope == SovereigntyTab.Region):
                if util.IsWormholeRegion(self.regionID):
                    text += regItem.itemName
                else:
                    text += (SHOW_INFO_URL % (regItem.typeID,
                     self.regionID,
                     ('<b>%s</b>' % regItem.itemName)))
            return text



    def CreateMenu(self):
        tabs = [[mls.SYSTEM,
          self.sr.regionalOverview,
          self,
          SovereigntyTab.SolarSystem],
         [mls.CONSTELLATION,
          self.sr.regionalOverview,
          self,
          SovereigntyTab.Constellation],
         [mls.REGION,
          self.sr.regionalOverview,
          self,
          SovereigntyTab.Region],
         [mls.WORLD,
          self.sr.regionalOverview,
          self,
          SovereigntyTab.World],
         [mls.UI_SHARED_CHANGES,
          self.sr.worldOverview,
          self,
          SovereigntyTab.Changes]]
        self.pushButtons = uicls.FlatButtonGroup(parent=self.sr.menu, align=uiconst.TOTOP, height=MENU_HEIGHT, padLeft=4, padRight=4)
        self.pushButtons.Startup(tabs)
        self.pushButtons.toggleEnabled = False



    def CreateLocationInfo(self):
        mapIconContainer = uicls.Container(name='mapIconContainer', parent=self.sr.location, align=uiconst.TORIGHT, pos=(0, 0, 32, 0), padding=(0, 0, 0, 5))
        self.sr.textContainer = uicls.Container(name='textContainer', parent=self.sr.location, align=uiconst.TOALL, pos=(0, 0, 0, 0), padding=(0, 0, 0, 0))
        btn = uix.GetBigButton(32, mapIconContainer)
        btn.anchors = uix.UI_ANCHRIGHT
        btn.autoPos = uix.AUTOPOSYCENTER
        btn.OnClick = self.OpenMap
        btn.hint = mls.UI_SHARED_MAP
        uix.MapSprite('7_4', btn.sr.icon)
        locationMenu = uicls.MenuIcon(size=24, ignoreSize=True)
        locationMenu.GetMenu = self.GetLocationMenu
        locationMenu.left = -5
        locationMenu.top = -3
        locationMenu.hint = ''
        self.sr.textContainer.children.append(locationMenu)
        self.sr.breadCrumbs = uicls.Label(name='label', text='', parent=self.sr.textContainer, fontsize=16, align=uiconst.TOTOP, padding=(15, 0, 0, 0), autoheight=1, boldlinks=0, autowidth=False, state=uiconst.UI_NORMAL)
        self.sr.dominatorText = uicls.Label(text='', parent=self.sr.textContainer, align=uiconst.TOTOP, height=16, fontsize=12, autoheight=False, state=uiconst.UI_NORMAL)



    def GetDominantAllianceName(self):
        sovID = sm.GetService('sov').GetDominantAllianceID(self.locationScope, self.regionID, self.constellationID, self.solarSystemID)
        if (sovID == 'none'):
            self.sovID = None
            return mls.NONE
        else:
            if (sovID == 'contested'):
                self.sovID = None
                return mls.UI_INFLIGHT_CONTESTED
            self.sovID = sovID
            typeID = const.typeAlliance
            if util.IsFaction(self.sovID):
                typeID = const.typeFaction
            sovName = cfg.eveowners.Get(sovID).name
            text = (SHOW_INFO_URL % (typeID,
             sovID,
             sovName))
            return text



    def UpdateLocationInfo(self):
        self.sr.breadCrumbs.text = self.CreateHeaderText()
        contestedState = ''
        sovHolder = None
        if (self.locationScope == SovereigntyTab.SolarSystem):
            contestedState = sm.GetService('sov').GetContestedState(self.solarSystemID)
            if (self.solarSystemID == session.solarsystemid2):
                sovInfo = sm.GetService('sov').GetSystemSovereigntyInfo(self.solarSystemID)
                if sovInfo:
                    typeID = const.typeAlliance
                    allianceID = sovInfo.allianceID
                    allianceName = cfg.eveowners.Get(sovInfo.allianceID).name
                    sovHolder = (SHOW_INFO_URL % (typeID,
                     allianceID,
                     allianceName))
        if (sovHolder is None):
            sovHolder = self.GetDominantAllianceName()
        self.sr.dominatorText.text = ('%s: <b>%s</b>%s' % (mls.SOVEREIGNTY_DOMINANTALLIANCE,
         sovHolder,
         contestedState))



    def CreateActiveKillInfo(self):
        leftContainer = uicls.Container(name='leftContainer', parent=self.sr.activekill, align=uiconst.TOALL, padding=(5, 0, 0, 0))
        rightContainer = uicls.Container(name='rightContainer', parent=self.sr.activekill, align=uiconst.TORIGHT, padding=(0, 0, 5, 0))
        uicls.Label(text=mls.SOVEREIGNTY_KILLSLAST24H, parent=leftContainer, align=uiconst.TOPLEFT, fontsize=12)
        uicls.Label(text=('%s (%s / %s)' % (mls.SOVEREIGNTY_CYNOFIELDSACTIVE,
         mls.UI_INFLIGHT_STRUCTURES,
         mls.UI_GENERIC_MODULES)), parent=leftContainer, align=uiconst.TOPLEFT, fontsize=12, top=14)
        self.killsText = uicls.Label(text='0 / 0', parent=rightContainer, align=uiconst.TOPRIGHT, fontsize=12)
        self.activeText = uicls.Label(text='0 / 0', parent=rightContainer, align=uiconst.TOPRIGHT, fontsize=12, top=14)
        maxwidth = max(self.killsText.width, self.activeText.width)
        rightContainer.width = maxwidth
        self.UpdateActiveKillInfo()



    def UpdateActiveKillInfo(self):
        if util.IsWormholeRegion(self.regionID):
            self.killsText.text = mls.UI_GENERIC_UNKNOWN
            self.activeText.text = mls.UI_GENERIC_UNKNOWN
        else:
            (kills, pods,) = sm.GetService('sov').GetKillLast24H(self.GetLocationFromScope())
            self.killsText.text = ('%d / %d' % (kills, pods))
            cynoResult = sm.GetService('sov').GetActiveCynos(self.GetLocationFromScope())
            self.activeText.text = ('%d / %d' % (cynoResult.cynoStructures, cynoResult.cynoModules))



    def GetBarColor(self, hasSov):
        if hasSov:
            return COLOR_LIGHT_BLUE
        else:
            return COLOR_DARK_BLUE



    def SetEndPointDates(self):
        uix.Flush(self.sr.dates)
        uicls.Label(text=util.FmtDate(blue.os.GetTime()), parent=self.sr.dates, align=uiconst.TORIGHT, left=0, top=0, fontsize=12, autowidth=False, autoheight=False)
        uicls.Label(text=util.FmtDate(blue.os.GetTime()), parent=self.sr.dates, align=uiconst.TOLEFT, left=0, top=0, fontsize=12, autowidth=False, autoheight=False)



    def _OnResize(self, *args):
        if hasattr(self, 'pushButtons'):
            self.pushButtons._AdjustButtons()
        self.ApplyContentPortion()



    def ShowStationsOutposts(self):
        (locationHeader, items,) = self.GetHeaderAndPrimedItems()
        self.sr.stationOutpostsScroll.sr.id = 'stationOutpostsScroll'
        scrolllist = []
        headers = [mls.UI_SHARED_MAPSOVEREIGNTY,
         locationHeader,
         mls.UI_GENERIC_STATIONS]
        cfg.eveowners.Prime([ item.allianceID for item in items ])
        stateSvc = sm.GetService('state')
        for item in items:
            kv = util.KeyVal(item)
            kv.ownerID = kv.allianceID
            locationName = cfg.evelocations.Get(item.locationID).name
            if (item.allianceID is not None):
                alliance = cfg.eveowners.Get(item.allianceID).name
            else:
                alliance = ''
            text = ('%s<t>%s<t><right>%d' % (alliance,
             locationName,
             item.stationCount))
            scrolllist.append((alliance, listentry.Get('SovereigntyEntry', {'line': 1,
              'label': text,
              'allianceID': item.allianceID,
              'stationCount': item.stationCount,
              'loss': False,
              'locationID': item.locationID,
              'scope': self.locationScope,
              'regionID': None,
              'flag': stateSvc.CheckStates(kv, 'flag')})))

        scrolllist = uiutil.SortListOfTuples(scrolllist)
        self.sr.stationOutpostsScroll.Load(contentList=scrolllist, headers=headers)
        self.sr.stationOutpostsScroll.ShowHint('')



    def ShowInfrastructureHubs(self):
        (locationHeader, items,) = self.GetHeaderAndPrimedItems()
        scrolllist = []
        for item in items:
            locationName = cfg.evelocations.Get(item.locationID).name
            scrolllist.append((locationName, listentry.Get('IndexEntry', {'label': locationName,
              'militaryPoints': item.militaryPoints,
              'industrialPoints': item.industrialPoints,
              'claimedFor': item.claimedFor,
              'locationID': item.locationID,
              'scope': self.locationScope})))

        scrolllist = uiutil.SortListOfTuples(scrolllist)
        scrolllist.insert(0, listentry.Get('HeaderEntry', {'systemHeader': locationHeader,
         'militaryHeader': mls.UI_TUTORIAL_MILITARY,
         'industryHeader': mls.UI_TUTORIAL_INDUSTRY,
         'claimTimeHeader': mls.SOVEREIGNTY_STRATEGIC}))
        self.sr.infrastructurehubsScroll.Load(contentList=scrolllist)



    def GetHeaderAndPrimedItems(self):
        locationID = self.GetLocationFromScope()
        locationHeader = ''
        if (self.locationScope == SovereigntyTab.SolarSystem):
            locationHeader = mls.SYSTEM
        elif (self.locationScope == SovereigntyTab.Constellation):
            locationHeader = mls.SYSTEM
        elif (self.locationScope == SovereigntyTab.Region):
            locationHeader = mls.CONSTELLATION
        elif (self.locationScope == SovereigntyTab.World):
            locationHeader = mls.REGION
        items = sm.GetService('sov').GetCurrentData(locationID)
        cfg.evelocations.Prime([ item.locationID for item in items ])
        return (locationHeader, items)



    def ShowChanges(self):
        self.sr.changesScroll.sr.id = 'changesScroll'
        scrolllist = []
        headers = []
        headers = [mls.UI_GENERIC_OWNER,
         mls.UI_GENERIC_REGION,
         mls.UI_GENERIC_SYSTEM,
         mls.UI_GENERIC_CHANGE,
         mls.UI_GENERIC_DATE]
        items = sm.GetService('sov').GetRecentActivity()
        solarSystemList = [ item.solarSystemID for item in items ]
        map = sm.GetService('map')
        regionList = [ map.GetRegionForSolarSystem(item) for item in solarSystemList ]
        cfg.evelocations.Prime((solarSystemList + regionList))
        ownerList = [ item.ownerID for item in items ]
        oldOwnerList = [ item.oldOwnerID for item in items ]
        cfg.eveowners.Prime((ownerList + oldOwnerList))
        stateSvc = sm.GetService('state')
        for (i, item,) in enumerate(items):
            systemName = cfg.evelocations.Get(item.solarSystemID).name
            ownerID = item.ownerID
            oldOwnerID = item.oldOwnerID
            regionID = regionList[i]
            region = cfg.evelocations.Get(regionID).name
            ownerChanges = []
            loss = False
            if (item.stationID is None):
                if (item.oldOwnerID is None):
                    ownerChanges.append(util.KeyVal(text=mls.SOVEREIGNTY_SOVGAIN, allianceID=ownerID, ownerID=ownerID, loss=False))
                else:
                    if (item.ownerID is None):
                        ownerChanges.append(util.KeyVal(text=mls.SOVEREIGNTY_SOVLOSS, allianceID=oldOwnerID, ownerID=oldOwnerID, loss=True))
            elif (item.oldOwnerID is None):
                ownerChanges.append(util.KeyVal(text=mls.SOVEREIGNTY_STATIONGAIN, corpID=ownerID, ownerID=ownerID, loss=False))
            elif (item.ownerID is not None):
                ownerChanges.append(util.KeyVal(text=mls.SOVEREIGNTY_STATIONLOSS, corpID=oldOwnerID, ownerID=oldOwnerID, loss=True))
                ownerChanges.append(util.KeyVal(text=mls.SOVEREIGNTY_STATIONGAIN, corpID=ownerID, ownerID=ownerID, loss=False))
            date = util.FmtDate(item.activityTime, 'ss')
            for kv in ownerChanges:
                ownerName = cfg.eveowners.Get(kv.ownerID).name
                text = ('%s<t>%s<t>%s<t>%s<t>%s' % (ownerName,
                 region,
                 systemName,
                 kv.text,
                 date))
                flag = stateSvc.CheckStates(kv, 'flag')
                scrolllist.append((ownerName, listentry.Get('SovereigntyEntry', {'line': 1,
                  'label': text,
                  'allianceID': kv.Get('allianceID', None),
                  'corpID': kv.Get('corpID', None),
                  'loss': kv.loss,
                  'locationID': item.solarSystemID,
                  'scope': self.locationScope,
                  'regionID': regionID,
                  'flag': stateSvc.CheckStates(kv, 'flag')})))


        scrolllist = uiutil.SortListOfTuples(scrolllist)
        self.sr.changesScroll.Load(contentList=scrolllist, headers=headers)
        self.sr.changesScroll.ShowHint('')



    def Refresh(self):
        self.UpdateLocationInfo()
        self.UpdateActiveKillInfo()
        if (self.locationScope == SovereigntyTab.Changes):
            self.ShowChanges()
        else:
            self.ShowStationsOutposts()
            self.ShowInfrastructureHubs()



    def OnSystemStatusChanged(self):
        self.Refresh()



    def OnSovereigntyChanged(self, solarSystemID, allianceID):
        self.UpdateLocationInfo()



    def OnSessionChanged(self, isremote, session, change):
        if ('solarsystemid2' in change):
            if not self.destroyed:
                self.Refresh()



    def OnStateSetupChance(self, *args):
        self.ShowStationsOutposts()



    def OpenMap(self, *args):
        if sm.GetService('map').ViewingStarMap():
            sm.GetService('map').Close()
        else:
            sm.GetService('map').OpenStarMap()
            sm.GetService('starmap').SetInterest((self.GetLocationFromScope() or const.locationUniverse))



    def GetLocationMenu(self, *args):
        m = []
        m.append([('%s %s' % (mls.UI_GENERIC_VIEW, mls.UI_SHARED_MAPCURRENTLOCTION)), self.ResetLocation])
        m.append((mls.SOVEREIGNTY_SOVEREIGNTY_SHOW_SOV_STARS_IN_MAP,
         self.ShowStarsInMap,
         ((STARMODE_FACTION, -1))))
        m.append((mls.SOVEREIGNTY_SHOW_SOV_TILES_IN_MAP, self.ShowSovTilesInMap))
        m.append((mls.SOVEREIGNTY_SHOW_CHANGES_IN_MAP,
         self.ShowStarsInMap,
         (STARMODE_SOV_CHANGE)))
        return m



    def ShowStarsInMap(self, starMode):
        mapSvc = sm.GetService('map')
        mapSvc.OpenStarMap()
        if mapSvc.IsOpen():
            starmap = sm.GetService('starmap')
            starmap.SetStarColorMode(starMode)
            starmap.SetInterest((self.GetLocationFromScope() or const.locationUniverse))



    def ShowSovTilesInMap(self):
        mapSvc = sm.GetService('map')
        mapSvc.OpenStarMap()
        if mapSvc.IsOpen():
            starmap = sm.GetService('starmap')
            starmap.SetTileMode(STARMODE_SOV_CHANGE)
            starmap.SetInterest((self.GetLocationFromScope() or const.locationUniverse))



    def ResetLocation(self):
        self.SetLocation(eve.session.solarsystemid2, eve.session.constellationid, eve.session.regionid)




